const  User  = require('../collection/user')
const { authLogin } = require('./../../routers/weixin/index')
const { createToken, varifyToken, removeEmptyValues, generateUUID } = require('../../utils/methold')
const Goods = require("../collection/goods");
const consola = require("consola");



/**
 * @author:  maybe
 * @date: 2024/1/8
 * @des: 由于解析token，获取用户id，所以抽离出来
 */
const getUserInfoByToken =  async(ctx) => {
    return new Promise(async (resolve,reject) => {
        const token = ctx.headers.authorization
        if (!token) return  reject() // 无效的token 失效
        const res = await varifyToken(token)
        // 解密token
        if(res && res.userInfo) {
            const openid = res.userInfo.openid
            const user = await User.findOne({openid})
            // 不存在用户,重新登录注册
            if (!user) {
                return  reject() //  无效的token
            }
            resolve(user)
        } else{
            return  reject() // 无效的token 失效
        }

    })

}

module.exports = {
    // login
    login: async (ctx) => {
        const {
            code,
        } = ctx.request.body
        const res = await authLogin(code)
        if (!res.data.openid) {
            ctx.body = {
                status: 401,
                msg: res.errmsg,
                data: res.data
            }
            return
        }
        const query = { openid: res.data.openid}
        const user = await User.findOne(query)
        // 已经存在直接返回token
        if (user) {
            const token  = await createToken(query)
            ctx.body = {
                status: 200,
                msg: '登录成功!' ,
                data: token
            }
            return
        }
        ctx.body = {
            status: 20001,
            msg: '登录信息异常' ,
            data: null
        }
    },
    /**
     * 用户首次登录+注册
     */
    loginInit:async (ctx) =>{
        const {
            code,
        } = ctx.request.body
        const res = await authLogin(code)
        if (!res.data.openid) {
            ctx.body = {
                status: 401,
                msg: res.errmsg,
                data: res.data
            }
            return
        }
        const user = {...ctx.request.body}
        delete user.code
        user.openid = res.data.openid
        const query = { openid: res.data.openid}
        const result = await User.findOne(query)
        // 已经存在直接返回token
        if (result) {
            const token  = await createToken(query)
            ctx.body = {
                status: 200,
                msg: '登录成功!' ,
                data: token
            }
            return
        }
        const newUser = new User(user)
        await newUser.save()
        const token = await createToken(query)
        consola.success(token,'token')
        ctx.body = {
            status: 200,
            msg: '登录成功',
            data: token
        }
    },


    logout: async (ctx) => {
        ctx.body = {
            status: 200,
            msg: '已成功退出',
            data: null
        }
    },
    //获取用户信息
    getUser: async(ctx)=> {
        const token = ctx.headers.authorization
        // 解密token
        const res = await varifyToken(token)
        if(res && res.userInfo) {
            const openid = res.userInfo.openid
            const _user = await User.findOne({openid})
            if(_user){
                ctx.body = {
                    status: 200,
                    msg: '成功',
                    data: {
                        nickName: _user.nickName,
                        gender: _user.gender,
                        avatarUrl: _user.avatarUrl,
                        phone:  _user.tel
                    }
                }
                return
            }
            ctx.body = {
                status: 20002 ,
                msg: '异常',
                data: null
            }

        }
        ctx.body = {
            status: 20001,
            msg: '登录信息异常,请重新登录',
            data: null
        }
        return {}
    },

    //修改用户信息
    editUser: async(ctx) =>{
        const token = ctx.headers.authorization
        // 解密token
        const res = await varifyToken(token)
        if(res && res.userInfo) {
            const openid = res.userInfo.openid
            let params = {
                ...ctx.request.body
            }
            params = removeEmptyValues(params)
            // 如果有图像，要先存在阿里云
            // if (params.avatarUrl) {
            //     const fileName = path.basename(params.avatarUrl)
            //     headers['x-oss-content-type'] = params.avatarUrl.split('.').pop().toLowerCase()
            //     console.log(headers,params.avatarUrl,'111')
            //     const resultFile = await client.put(`images/` + fileName, fs.createReadStream(params.avatarUrl)
            //         ,{headers}
            //     );
            //     console.log(resultFile,'resultFile')
            //     // 获取阿里云给的url【目前阿里云只有3个月】
            //     if(resultFile && resultFile.res.status == 200) {
            //         params.avatarUrl = resultFile.url
            //     }
            // }
            const result = await User.updateOne({openid: openid},{ $set:params })
            if(result.acknowledged && result.modifiedCount) {
                ctx.body = {
                    status: 200,
                    data: {},
                    msg: '修改成功'
                }
            }else {
                ctx.body = {
                    status: 'error',
                    data: {},
                    msg: '数据异常'
                }
            }
            return
        }

    },
    /**
     * @author:  maybe
     * @date: 2024/1/8 
     * @des: 获取用户购物车数据
     */
    getShipCart: async (ctx) => {
        try {
            const token = ctx.headers.authorization
            const res = await varifyToken(token)
            // 解密token
            if(res && res.userInfo) {
                const openid = res.userInfo.openid
                const user = await User.findOne({openid})
                // 不存在用户,重新登录注册
                if (!user) {
                    ctx.body = {
                        status: 20002 ,
                        msg: '异常',
                        data: null
                    }
                    return
                }
                //  存在购物车数据
                const  ids = user.shoppingCart.map(item => {
                    return item.goodsId
                })
                let result = await Goods.find({ _id: { "$in": ids } })
                // 查询到所有的商品
                let shoppingCart = user.shoppingCart
                if (ids.length !== result.length) {
                    const deleteIds = result.map(item => {
                        return item._id.toString()
                    })
                    shoppingCart = shoppingCart.filter(item => deleteIds.includes(item.goodsId))
                    await User.updateOne({ openid: user.openid },{ $set:{ shoppingCart } })
                }
                result = result.map(item => {
                    const _item = shoppingCart.find(itm => itm.goodsId === item._id.toString())
                    const count = _item.count | 1
                    return {
                        goodsId: item._id.toString(),
                        goodsName:  item.goodsName,
                        goodsImg: item.goodsImg,
                        status: item.status,
                        des: item.des,
                        weight: item.weight,
                        price: item.price,
                        discount: item.discount,
                        count
                    }
                })
                ctx.body = {
                    status: 200 ,
                    msg: '成功',
                    data: result
                }
            }
        }
        catch (error){
            ctx.body = {
                status: 200 ,
                msg: '成功',
                data: []
            }
        }
    },
    /**
     * @author:  maybe
     * @date: 2024/1/9 
     * @des: 获取要去结算的单子
     */
    getShipGoods: async (ctx) => {
        const token = ctx.headers.authorization
        const res = await varifyToken(token)
        // 解密token
        if(res && res.userInfo) {
            const openid = res.userInfo.openid
            const user = await User.findOne({openid})
            // 不存在用户,重新登录注册
            if (!user) {
                ctx.body = {
                    status: 20002 ,
                    msg: '异常',
                    data: null
                }
                return
            }
            const { ids } = ctx.request.query
            if (!ids) {
                 ctx.body = {
                    status: 200 ,
                    msg: '成功',
                    data: []
                }
                return
            }
            const result = await Goods.find({ _id: { "$in": ids.split(',') } })
            if (result && result.length) {
                 const goodsData = user.shoppingCart.filter(item => ids.split(',').includes(item.goodsId))
                 let amount =  0
                 let  payAmount = 0
                 const data = result.map((item,index) => {
                     const _item = goodsData.find(itm => itm.goodsId === item._id.toString())
                     const count = _item.count | 1
                     amount += (parseInt(count) * parseFloat(item.price))
                     payAmount += (parseInt(count) * parseFloat(item.price) * parseFloat(item.discount) / 10)
                     return {
                         goodsId: item._id.toString(),
                         goodsName:  item.goodsName,
                         goodsImg: item.goodsImg,
                         status: item.status,
                         des: item.des,
                         weight: item.weight,
                         price: item.price,
                         discount: item.discount,
                         count
                     }
                 })

                 ctx.body = {
                     status: 200 ,
                     msg: '成功',
                     data: {
                         list: data,
                         amount: amount.toFixed(2),
                         payAmount: payAmount.toFixed(2),
                     }
                 }
            } else {
                ctx.body = {
                    status: 200 ,
                    msg: '成功',
                    data: []
                }
            }
        }

    },
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 添加购物车
     */
    addShipCart: async (ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        const {
            goodsId,
            count
        } = ctx.request.body
        const  isExist = user.shoppingCart.some(item => item.goodsId === goodsId)
        if (isExist) {
            ctx.body = {
                status: 'error',
                data: null,
                msg: '商品已存在购物车，请去购物车编辑'
            }
            return
        }
        const goods = await Goods.findOne({_id: goodsId})
        // 不存在
        if (!goods) {
            ctx.body = {
                status: 'error',
                data: {},
                msg: '商品信息异常'
            }
            return
        }
        // 已经下架
        if(goods.status === 0) {
            ctx.body = {
                status: 'error',
                data: {},
                msg: '商品已经下架,不允许添加'
            }
            return
        }
        const shoppingCart = user.shoppingCart
        shoppingCart.push({
            goodsId,
            count,
            createTime: new Date(),
            updateTime: new Date(),
        })
       await User.updateOne({ openid: user.openid },{ $set:{shoppingCart} })
        ctx.body = {
            status: 200,
            msg: '添加购物车成功',
        }
    },
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 修改购物车
     */
    editShipCart: async (ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        const {
            goodsId,
            count
        } = ctx.request.body
        const  shoppingCart = user.shoppingCart.map(item => {
            if(item.goodsId === goodsId) item.count = count
            return item
        }) || []
        await User.updateOne({ openid: user.openid },{ $set:{ shoppingCart} })
        ctx.body = {
            status: 200,
            msg: '修改购物车成功',
        }
    },
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 删除购物车
     */
    deleteShipCart: async (ctx) => {
        try {
            const user = await getUserInfoByToken(ctx)
            if(!user) {
                ctx.body = {
                    status: 20001 ,
                    msg: '无效的token,请重新登录',
                    data: null
                }
                return
            }
            const {
                goodsId,
            } = ctx.request.query
            const  shoppingCart = user.shoppingCart.filter(item => item.goodsId !== goodsId) || []
            await User.updateOne({ openid: user.openid },{ $set:{ shoppingCart} })
            ctx.body = {
                status: 200,
                msg: '删除购物车成功',
            }
        }
        catch (error) {
            ctx.body = {
                status: 500,
                msg: '删除失败',
                data: []
            }
        }

    },
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 获取地址
     */
    getAddress: async(ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        ctx.body = {
            status: 200,
            data: user.deliveryAddress.sort((a, b) => b.default - a.default),
            msg: '成功'
        }
    } ,
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 新增地址
     */
    addAddress: async(ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        let  deliveryAddress = user.deliveryAddress
        if (Number(ctx.request.body.default)) {
            deliveryAddress = user.deliveryAddress.map(item => {
                item.default = 0
                return item
            })
        }
        deliveryAddress.push({
            ...ctx.request.body,
            addressId: generateUUID()
        })
        await User.updateOne({ openid: user.openid },{ $set:{ deliveryAddress} })
        ctx.body = {
            status: 200,
            msg: '修改地址成功',
        }
    } ,
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 修改地址
     */
    editAddress: async(ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        const  deliveryAddress = user.deliveryAddress.map(item => {
            if (Number(ctx.request.body.default)) {
                item.default = 0
            }
            if(item.addressId === ctx.request.body.addressId) {
                return  ctx.request.body
            }
            return item
        })
        await User.updateOne({ openid: user.openid },{ $set:{ deliveryAddress} })
        ctx.body = {
            status: 200,
            msg: '修改地址成功',
        }
    } ,
    /**
     * @author:  maybe
     * @date: 2024/1/8
     * @des: 删除地址
     */
    deleteAddress: async(ctx) => {
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        const {
            addressId,
        } = ctx.request.query
        const  deliveryAddress = user.deliveryAddress.filter(item => item.addressId !== addressId) || []
        await User.updateOne({ openid: user.openid },{ $set:{ deliveryAddress} })
        ctx.body = {
            status: 200,
            msg: '删除地址成功',
        }
    } ,

}
